package com.dzsw.javabase.str;

import java.io.File;

public class ReplaceSample {

    public static void main(String[] args) {
        String str = "this|is|a|sample.";
        System.out.println(str.replace("|", " ")); // 全部替换
        System.out.println(str.replaceAll("\\|", " ")); // 全部替换，正则表达式

        String str1 = "/icon/logo.gif";
        System.out.println(str1.replace("/", File.separator)); // 全部替换
        System.out.println(str1.replaceAll("/\\//", File.separator)); // 全部替换，正则表达式

        String str2 = "SUM({$}12,{$}13,{$}14,{$}15)";
        System.out.println(str2.replace("{$}", "AB"));
        System.out.println(replaceAll(str2, "{$}", "AB"));
    }

    public static String replaceAll(String strInput, String strRegex, String strReplacement) {
        if (strInput == null) {
            return null;
        }

        int index = strInput.lastIndexOf(strRegex);
        while (index != -1) {
            String strTmp1 = strInput.substring(0, index);
            String strTmp2 = strInput.substring(index + strRegex.length());
            strInput = strTmp1 + strReplacement + strTmp2;

            index = strInput.lastIndexOf(strRegex);
        }
        return strInput;
    }
}
